#! /user/bin/python3
# coding-utf-8
# @Time = 2025/4/15 10:51
# @Author:Poolaris

import pymysql
from common.yaml_config import GetConf


class MysqlOperate:
    def __init__(self):
        mysql_conf = GetConf().get_mysql()
        self.host = mysql_conf["host"]
        self.db = mysql_conf["db"]
        self.user = mysql_conf["user"]
        self.password = mysql_conf["password"]
        self.port = mysql_conf["port"]
        self.conn = None
        self.cur = None

    def __conn_db(self):
        try:
            self.conn = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                db=self.db,
                port=self.port,
                charset="utf8"
            )
        except Exception as e:
            print(e)
            return False
        self.cur = self.conn.cursor()
        # 在 PyMySQL 中，‌cursor（游标）‌ 是一个用于执行 SQL 语句并管理查询结果的核心对象。它类似于一个“指针”，允许你逐行访问数据库的返回结果
        return True

    def __close_conn(self):
        self.cur.close()
        self.conn.close()
        return True

    def __commit(self):
        self.conn.commit()
        return True

    def query(self,sql):
        """
        查询
        :param sql:
        :return:
        """
        self.__conn_db()
        self.cur.execute(sql)
        # query_data = self.fetchall()
        query_data = self.cur.fetchall()
        if query_data == ():
            query_data = None
            print("没有获取到数据，表为空")
        else:
            pass
        self.__close_conn()
        return query_data

    def insert_update_table(self, sql):
        self.__conn_db()
        self.cur.execute(sql)
        self.__commit()
        self.__close_conn()


if __name__ == '__main__':
    print(MysqlOperate().query("select * from user"))
    result = MysqlOperate().query("select * from user")
    print(result[0][1])